package com.bigboss.knowstar.controller;

import com.bigboss.knowstar.entity.Article;
import com.bigboss.knowstar.entity.model.APIResult;
import com.bigboss.knowstar.exception.ArticleException;
import com.bigboss.knowstar.service.impl.ArticleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

import static com.bigboss.knowstar.utils.ValidateData.validateData;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;

    @PostMapping("")
    public APIResult articleCreate(@RequestBody @Validated Article article, BindingResult result) {
        try {
            ArrayList<String> data = validateData(result);
            if (data != null) {
                return APIResult.error(data);
            }
            articleService.createArticle(article);
            return APIResult.success("文章创建成功");
        } catch (ArticleException e) {
            return APIResult.error("文章创建失败:" + e.getMessage());
        }
    }

    @PutMapping("/{Aid}")
    public APIResult articleUpdate(@PathVariable Integer Aid, @RequestBody Map<String, Object> fields) {
        try {
            articleService.updateArticle(Aid, fields);
            return APIResult.success("文章更新成功");
        } catch (ArticleException e) {
            return APIResult.error("文章更新失败:" + e.getMessage());
        }
    }

    @DeleteMapping("/{Aid}")
    public APIResult articleDelete(@PathVariable Integer Aid) {
        try {
            articleService.deleteArticle(Aid);
            return APIResult.success("文章删除成功");
        } catch (ArticleException e) {
            return APIResult.error("文章删除失败:" + e.getMessage());
        }
    }

    @GetMapping("/{Aid}")
    public APIResult articleQueryByAid(@PathVariable Integer Aid) {
        try {
            Article article = articleService.getArticle(Aid);
            return APIResult.success(article);
        } catch (ArticleException e) {
            return APIResult.error("文章查询失败:" + e.getMessage());
        }
    }
}
